#coding:utf-8
from rest_framework import generics, viewsets, mixins, status
from django.contrib.auth import login
from rest_framework.response import Response
from rest_framework.views import APIView
from .serializers import *


class LoginViewSet(APIView):
    queryset = User.objects.all()
    serializer_class = LoginSerializer


    def post(self, request):
        try:
            username = request.data.get('username')
            password = request.data.get('password')
            user = User.objects.get(username__iexact=username)
            if user.check_password(password):
                login(request, user)
                print(user)
                serializer = LoginSerializer({'id': user.id, 'username': user.username})
                responseData = serializer.data
                responseData['sessionId'] = request.session.session_key
                response = Response(responseData)
                return response
            return Response(status=status.HTTP_401_UNAUTHORIZED)
        except User.DoesNotExist:
            return Response(status=status.HTTP_401_UNAUTHORIZED)


class UserViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows users to be viewed or edited.
    """
    queryset = User.objects.all().order_by('-date_joined')
    serializer_class = UserSerializer


class GroupViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows groups to be viewed or edited.
    """
    queryset = Group.objects.all()
    serializer_class = GroupSerializer